import axios from 'axios'
const qs = require('qs')
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
// import { UserModule } from "@/store/modules/user";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: "http://api.alldong.com/",
  headers: { 'content-type': 'application/x-www-form-urlencoded' }
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    const defaultParams = {
      platform: 'pc'
    }
    // // 刷新token
    // if (getTimeDate() && getToken()) {
    //   const timeout = Number(getTimeDate())
    //   const date = (timeout - new Date().getTime() / 1000)
    //   if (date <= 0) {
    //     toLogin()
    //   }
    // }
    defaultParams.manage_token = getToken()

    if (config.method === 'get') {
      if (!config.params) {
        config.params = defaultParams
      } else {
        config.params = Object.assign({}, config.params, defaultParams)
      }
    } else if (config.method === 'post') {
      if (!config.data) {
        config.data = defaultParams
      } else {
        config.data = Object.assign({}, config.data, defaultParams)
      }
      config.data = qs.stringify(config.data)
    }

    return config
  },
  error => {
    Promise.reject(error)
  }
)
// Response interceptors
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== '200') {
      Message({
        message: res.message,
        type: 'error'
      })
      if (res.code === '301') {
        // UserModule.ResetToken();
        // toLogin()
      }
      return Promise.reject(res.message)
    } else {
      return Promise.resolve(response.data.data)
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default function request(config) {
  return service(config)
}
